<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
    
  
  <link href="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="JAVA,IO," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="Java中的IO具有很多的类，在之前的学习中经常被其弄得不知所云，因此问度娘找了一幅JavaIO流的关系图，以加深对JavaIO的理解

File类java.io.File类只用于表示文件（目录）的信息（名称，大小等），不能用于文件内容的访问
File读取一个目录，File有多个构造函数，不但可读取目录，同时还可以读取文件//在window系统中书写路径的时候需要使用“\\”表示分隔符，因为涉及到">
<meta property="og:type" content="article">
<meta property="og:title" content="Java-IO学习笔记">
<meta property="og:url" content="https://zitongchen.github.io/2017/08/19/Java-IO学习笔记/index.html">
<meta property="og:site_name" content="Tony's Notes">
<meta property="og:description" content="Java中的IO具有很多的类，在之前的学习中经常被其弄得不知所云，因此问度娘找了一幅JavaIO流的关系图，以加深对JavaIO的理解

File类java.io.File类只用于表示文件（目录）的信息（名称，大小等），不能用于文件内容的访问
File读取一个目录，File有多个构造函数，不但可读取目录，同时还可以读取文件//在window系统中书写路径的时候需要使用“\\”表示分隔符，因为涉及到">
<meta property="og:image" content="https://static.oschina.net/uploads/img/201707/10072846_0eWJ.jpg">
<meta property="og:updated_time" content="2017-09-16T10:20:34.232Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java-IO学习笔记">
<meta name="twitter:description" content="Java中的IO具有很多的类，在之前的学习中经常被其弄得不知所云，因此问度娘找了一幅JavaIO流的关系图，以加深对JavaIO的理解

File类java.io.File类只用于表示文件（目录）的信息（名称，大小等），不能用于文件内容的访问
File读取一个目录，File有多个构造函数，不但可读取目录，同时还可以读取文件//在window系统中书写路径的时候需要使用“\\”表示分隔符，因为涉及到">
<meta name="twitter:image" content="https://static.oschina.net/uploads/img/201707/10072846_0eWJ.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zitongchen.github.io/2017/08/19/Java-IO学习笔记/"/>





  <title> Java-IO学习笔记 | Tony's Notes </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Tony's Notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://zitongchen.github.io/2017/08/19/Java-IO学习笔记/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avater.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tony's Notes">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Java-IO学习笔记
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-19T00:00:00+08:00">
                2017-08-19
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Java/" itemprop="url" rel="index">
                    <span itemprop="name">Java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2017/08/19/Java-IO学习笔记/" class="leancloud_visitors" data-flag-title="Java-IO学习笔记">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Java中的IO具有很多的类，在之前的学习中经常被其弄得不知所云，因此问度娘找了一幅JavaIO流的关系图，以加深对JavaIO的理解</p>
<p><img src="https://static.oschina.net/uploads/img/201707/10072846_0eWJ.jpg" alt="输入图片说明" title="在这里输入图片标题"></p>
<h1 id="File类"><a href="#File类" class="headerlink" title="File类"></a>File类</h1><p>java.io.File类只用于表示文件（目录）的信息（名称，大小等），不能用于文件内容的访问</p>
<p>File读取一个目录，File有多个构造函数，不但可读取目录，同时还可以读取文件<br><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="comment">//在window系统中书写路径的时候需要使用“\\”表示分隔符，因为涉及到转义字符</span></div><div class="line">File file1 = <span class="keyword">new</span> File(<span class="string">"e:\\javaio\\filedemo"</span>);</div><div class="line"><span class="comment">//创建一级目录，若是想创建多级目录使用file1.mkdirs();</span></div><div class="line">file1.mkdir();</div><div class="line">File file2 = <span class="keyword">new</span> File(<span class="string">"e:\\javaio\\filedemo.txt"</span>);</div><div class="line"><span class="comment">//可以使用一个目录参数，一个文件名的参数读取文本文件</span></div><div class="line">File file3 = <span class="keyword">new</span> File(<span class="string">"e:\\javaio"</span>,<span class="string">"filedemo.txt"</span>);</div><div class="line"><span class="comment">//创建一个新的文本文件</span></div><div class="line">file3.createNewFile()</div><div class="line"><span class="comment">//获取文件的绝对路径</span></div><div class="line">file3.getAbsolutePath</div></pre></td></tr></table></figure></p>
<h1 id="RandomAccessFile"><a href="#RandomAccessFile" class="headerlink" title="RandomAccessFile"></a>RandomAccessFile</h1><p>RandomAccessFile提供了对文件内容的访问，即可读文件，也可写文件，同时支持随机访问文件，可以访问文件的任意位置</p>
<h2 id="Java文件模型"><a href="#Java文件模型" class="headerlink" title="Java文件模型"></a>Java文件模型</h2><ul>
<li>在硬盘上的文件是以byte字节数组存储的，是数据集合</li>
<li>打开文件有两种模式，一种是“rw”(读写),另一种是“r”(只读)<figure class="highlight java"><table><tr><td class="code"><pre><div class="line">RandomAccessFile raf = <span class="keyword">new</span> RandomAccessFile(file,<span class="string">"rw"</span>);</div></pre></td></tr></table></figure>
</li>
</ul>
<p>上述的RandomAccessFile使用了读写的方式，来进行对file的操作，打开文件时指针在开头pointer = 0</p>
<ul>
<li>raf.write(int) —-&gt; 只写一个字节（后8位），同时指针指向下一个位置，准备继续写入</li>
<li>int b = raf.read() —-&gt; 读取一个字节</li>
</ul>
<h2 id="基本类型的序列化"><a href="#基本类型的序列化" class="headerlink" title="基本类型的序列化"></a>基本类型的序列化</h2><ul>
<li>将类型int转换成4byte或将其他数据类型转换成byte的过程称为序列化，数据 —-&gt; n byte</li>
<li>将n 个 byte转换成一个数据的过程称为反序列化，n byte —–&gt; 数据</li>
<li>RandomAccessFile提供基本类型的读写方法，可以将基本类型数据序列化到文件或者将文件内容反序列化为数据</li>
</ul>
<p>RamdomAccessFile基本操作演示：<br><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RandomAccessFileSeriaDemo</span> </span>&#123;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span><span class="keyword">throws</span> IOException </span>&#123;</div><div class="line">		File demo = <span class="keyword">new</span> File(<span class="string">"demo"</span>);</div><div class="line">		<span class="keyword">if</span>(!demo.exists()) &#123;</div><div class="line">			demo.mkdirs();</div><div class="line">		&#125;</div><div class="line">		File file = <span class="keyword">new</span> File(demo,<span class="string">"raf.dat"</span>);</div><div class="line">		<span class="keyword">if</span>(file.exists()) &#123;</div><div class="line">			file.createNewFile();</div><div class="line">		&#125;</div><div class="line">		<span class="comment">//使用读写的方式读取file文件</span></div><div class="line">        RandomAccessFile raf = <span class="keyword">new</span> RandomAccessFile(file, <span class="string">"rw"</span>);</div><div class="line">		<span class="comment">//序列化一个16进制的整型</span></div><div class="line">		<span class="keyword">int</span> i =<span class="number">0x7ffffff</span>;</div><div class="line">		raf.write(i &gt;&gt;&gt; <span class="number">24</span>);</div><div class="line">		raf.write(i &gt;&gt;&gt; <span class="number">16</span>);</div><div class="line">		raf.write(i &gt;&gt;&gt; <span class="number">8</span>);</div><div class="line">		raf.write(i);</div><div class="line">		System.out.println(raf.getFilePointer());</div><div class="line">		</div><div class="line">		<span class="comment">//反序列化</span></div><div class="line">		raf.seek(<span class="number">0</span>);<span class="comment">//设置文件指针从0开始</span></div><div class="line">        <span class="keyword">int</span> i = <span class="number">0</span>;</div><div class="line">		<span class="comment">//raf的每次读取只能读取一个字节，int类型有4个字节，所以需要读4次,并或0</span></div><div class="line">        <span class="keyword">int</span> b = raf.read();</div><div class="line">		i = i | (b &lt;&lt; <span class="number">24</span>);</div><div class="line">		b = raf.read();</div><div class="line">		i = i | (b &lt;&lt; <span class="number">16</span>);</div><div class="line">		b = raf.read();</div><div class="line">		i = i | (b &lt;&lt; <span class="number">8</span>);</div><div class="line">		b = raf.read();</div><div class="line">		i = i | b;</div><div class="line">        <span class="comment">//打印出i的16进制</span></div><div class="line">		System.out.println(Integer.toHexString(i));</div><div class="line">		<span class="comment">//从置指针，以读取int的类型的方式读取数据</span></div><div class="line">		raf.seek(<span class="number">0</span>);</div><div class="line">		System.out.println(raf.readInt());</div><div class="line">		System.out.println(raf.getFilePointer());</div><div class="line">		raf.close();</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>Java的操作符：</p>
<ul>
<li>&amp;（与） 输入数据的对应位是1时，输出1，其他输出0</li>
<li>| （或）输入数据的对应位是0时，输出0，其他输出1</li>
<li>^ （异或）数据数据的对应位相反时（即一个是0 ，一个是1），输出1，其他输出0</li>
<li>~ （非）取反，输入1，输出0；输入0 ，输出1</li>
<li>&lt;&lt; (左移位) 按照右侧指定的位数，向左移，低位补0</li>
<li><code>&gt;&gt;</code> (带符号右移）操作数为正，高位补0，操作数为负高位补1</li>
<li><code>&gt;&gt;&gt;</code> (无符合右移）无论正负，高位补0</li>
</ul>
<h1 id="字节流"><a href="#字节流" class="headerlink" title="字节流"></a>字节流</h1><ul>
<li>InputStream抽象了应用程序读取数据的方式</li>
<li>OutputStream抽象了应用程序写出数据的方式</li>
<li>EOF = End 读到-1就表示读到文本内容结尾</li>
</ul>
<p>输入流基本方法：</p>
<ul>
<li>int b = in.read();读取一个字节无符合填充到int底八位，-1是EOF</li>
<li>in.read(byte[] buf);从流中读取buf.length个字节数据放进数组中，返回读取到的字节总数</li>
<li>in.read(byte[] buf,int start, int size)</li>
</ul>
<p>输出流基本方法：</p>
<ul>
<li>out.write(int b) 写出一个byte到流，b到底8位</li>
<li>out.write(byte[] buf)就buf字节数据写入到流中</li>
<li>out.write(byte[] buf, int start, int size)</li>
</ul>
<p>FileInputStream 具体实现了在文件上读取数据，读取的是byte数据，是对InputStream的第一层实现，实现了InputStream的基本方法<br><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="comment">// 读取指定文件内容，按照16进制输出到控制台, 并且每输出10个byte换行, 单字节读取不适合大文件，大文件效率很低</span></div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printHex</span><span class="params">(String fileName)</span> <span class="keyword">throws</span> IOException</span>&#123;</div><div class="line">		<span class="comment">//把文件作为字节流进行读操作</span></div><div class="line">		FileInputStream in = <span class="keyword">new</span> FileInputStream(fileName);</div><div class="line">		<span class="keyword">int</span> b ;</div><div class="line">		<span class="keyword">int</span> i = <span class="number">1</span>;</div><div class="line">		<span class="keyword">while</span>((b = in.read())!=-<span class="number">1</span>)&#123;</div><div class="line">			<span class="keyword">if</span>(b &lt;= <span class="number">0xf</span>)&#123;</div><div class="line">				<span class="comment">//单位数前面补0</span></div><div class="line">				System.out.print(<span class="string">"0"</span>);</div><div class="line">			&#125;</div><div class="line">			System.out.print(Integer.toHexString(b)+<span class="string">"  "</span>);</div><div class="line">			<span class="keyword">if</span>(i++%<span class="number">10</span>==<span class="number">0</span>)&#123;</div><div class="line">				System.out.println();</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line">		in.close();</div><div class="line">	&#125;</div></pre></td></tr></table></figure></p>
<p>FileOutputStream 实现了向文件中写出byte数据的方法，是对OutputStream的第一层实现，实现了OutputStream的方法<br><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="comment">//如果该文件不存在，则直接创建，如果存在，删除后创建</span></div><div class="line">FileOutputStream out = <span class="keyword">new</span> FileOutputStream(<span class="string">"demo/out.dat"</span>);</div><div class="line"><span class="comment">//FileOutputStream写的是一个字节</span></div><div class="line">out.write(<span class="string">'A'</span>);<span class="comment">//写出了'A'的低八位</span></div><div class="line">out.write(<span class="string">'B'</span>);<span class="comment">//写出了'B'的低八位</span></div></pre></td></tr></table></figure></p>
<p>在日常的使用中，文件的读取与写入都是使用字节数组批量处理字节<br><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="comment">//文件的拷贝，使用字节数据对字节进行批量读写操作</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">copyFile</span><span class="params">(File srcFile, File destFile)</span> <span class="keyword">throws</span> IOException</span>&#123;</div><div class="line">		<span class="keyword">if</span>(!srcFile.exists()) &#123;</div><div class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"文件:"</span> + srcFile + <span class="string">"不存在"</span>);</div><div class="line">		&#125;</div><div class="line">		<span class="keyword">if</span>(!destFile.isFile()) &#123;</div><div class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(srcFile + <span class="string">"不是文件"</span>);</div><div class="line">		&#125;</div><div class="line">		FileInputStream in = <span class="keyword">new</span> FileInputStream(srcFile);</div><div class="line">		FileOutputStream out = <span class="keyword">new</span> FileOutputStream(destFile);</div><div class="line">		<span class="keyword">byte</span>[] buf = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">2</span> * <span class="number">1024</span>];</div><div class="line">		<span class="keyword">int</span> b ;</div><div class="line">		<span class="keyword">while</span>((b = in.read(buf, <span class="number">0</span>, buf.length)) != -<span class="number">1</span>) &#123;</div><div class="line">			out.write(buf, <span class="number">0</span>, b);</div><div class="line">		&#125;</div><div class="line">		in.close();</div><div class="line">		out.close();</div><div class="line">	&#125;</div></pre></td></tr></table></figure></p>
<p>DataOutputStream/DataInputStream是对流功能的扩展，可以更加方便读写int,long,字符等数据类型; DataInputStream是继承了FileInputStream类,其构造函数需要一个输入流;DataOutputStream是继承了FileOutputStream类，其构造函数需要一个输出流<br><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="comment">//DataInputStream继承了FileInputStream类,其构造函数需要一个输入流</span></div><div class="line">DataInputStream dis = <span class="keyword">new</span> DataInputStream(<span class="keyword">new</span> FileInputStream(file));</div><div class="line"><span class="comment">//对流进行了扩展，可以很方便的读取直接读取到基本类型</span></div><div class="line"><span class="keyword">int</span> i = dis.readInt();</div><div class="line">System.out.println(i);</div><div class="line">dis.close()</div><div class="line"></div><div class="line"><span class="comment">//DataOutputStream继承了FileOutputStream类,其构造函数需要一个输出流</span></div><div class="line">DataOutputStream dos = <span class="keyword">new</span> DataOutputStream(<span class="keyword">new</span> FileOutputStream(file));</div><div class="line">dos.writeInt(<span class="number">10</span>);</div><div class="line"><span class="comment">//采用UTF-8编码写出</span></div><div class="line">dos.writeUTF(<span class="string">"中国"</span>);</div><div class="line"><span class="comment">//采用utf-16be编码写出</span></div><div class="line">dos.writeChars(<span class="string">"中国"</span>);</div><div class="line">dos.close();</div></pre></td></tr></table></figure></p>
<p>BufferedInputStream/BufferedInputStream 这两个流类为IO提供了带缓冲区的操作，一般打开文件进行文件的写入或读取操作时，都会加上缓冲，这种流模式提高了IO的性能<br><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="comment">//使用带缓冲区的方式拷贝文件</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">copyFileByBuffer</span><span class="params">(File srcFile,File destFile)</span><span class="keyword">throws</span> IOException</span>&#123;</div><div class="line">		<span class="keyword">if</span>(!srcFile.exists())&#123;</div><div class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"文件:"</span>+srcFile+<span class="string">"不存在"</span>);</div><div class="line">		&#125;</div><div class="line">		<span class="keyword">if</span>(!srcFile.isFile())&#123;</div><div class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(srcFile+<span class="string">"不是文件"</span>);</div><div class="line">		&#125;</div><div class="line">		BufferedInputStream bis = <span class="keyword">new</span> BufferedInputStream(</div><div class="line">				<span class="keyword">new</span> FileInputStream(srcFile));</div><div class="line">		BufferedOutputStream bos = <span class="keyword">new</span> BufferedOutputStream(</div><div class="line">				<span class="keyword">new</span> FileOutputStream(destFile));</div><div class="line">		<span class="keyword">int</span> c ;</div><div class="line">		<span class="keyword">while</span>((c = bis.read())!=-<span class="number">1</span>)&#123;</div><div class="line">			bos.write(c);</div><div class="line">			bos.flush();<span class="comment">//刷新缓冲区</span></div><div class="line">		&#125;</div><div class="line">		bis.close();</div><div class="line">		bos.close();</div><div class="line">	&#125;</div></pre></td></tr></table></figure></p>
<p>FileOutputStream —write()方法相当于一滴一滴地把水“转移”过去</p>
<p>DateOutputStream –&gt;writeXxx()方法会方便一些，相当于一瓢一瓢的把水“转移”过去</p>
<p>BufferedOutputStream —&gt;write()方法更方便，相当于一瓢一瓢的放到桶里，再一桶一桶的倒入另一个缸中，性能提高了</p>
<p>#字符流<br>java的文本（char）是16位无符号整数，是字符的unicode编码（双字节编码），文件是byte数组的数据序列，文本文件是文本（char）序列按照某种编码方案（utf-8,utf-16be,gbk）序列化为byte存储的结果</p>
<p>字符流（Reader Writer）： 操作的是文本文件，字符的处理，一次处理一个字符，字符底层仍然是字节序列</p>
<p>字符流的实现：</p>
<ul>
<li>InputStreamReader 完成byte流解析为char流，按照编码解析；OutputStreamWriter 提供char流到byte流，按照编码处理</li>
<li>FileReader/FileWriter</li>
<li>字符流的过滤器：BufferedReader —readLine 一次读一行；BufferedReader /PrintWriter —&gt;一次写一行</li>
</ul>
<p>InputStreamReader/OutputStreamWtriter的代码演示：<br><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">InputAndOutputReaderDemo</span> </span>&#123;</div><div class="line"></div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException </span>&#123;</div><div class="line">		</div><div class="line">		FileInputStream in = <span class="keyword">new</span> FileInputStream(<span class="string">"demo/reader.txt"</span>);</div><div class="line">		FileOutputStream out = <span class="keyword">new</span> FileOutputStream(<span class="string">"demo/writer.txt"</span>);</div><div class="line">		InputStreamReader reader = <span class="keyword">new</span> InputStreamReader(in);</div><div class="line">		OutputStreamWriter writer = <span class="keyword">new</span> OutputStreamWriter(out);</div><div class="line">		<span class="keyword">int</span> c;</div><div class="line">                <span class="comment">/*</span></div><div class="line">		while ((c = reader.read()) != -1) &#123;</div><div class="line">			System.out.print((char)c)｝</div><div class="line">			writer.write(c);</div><div class="line">		&#125;</div><div class="line">                */</div><div class="line">        <span class="comment">//使用字符数组，批量处理</span></div><div class="line">		<span class="keyword">char</span>[] buf = <span class="keyword">new</span> <span class="keyword">char</span>[<span class="number">1024</span>];</div><div class="line">		<span class="keyword">while</span>((c = reader.read(buf)) != -<span class="number">1</span>) &#123;</div><div class="line">			writer.write(buf, <span class="number">0</span>, c);</div><div class="line">		&#125;</div><div class="line">		reader.close();</div><div class="line">		writer.close();</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>BufferReader/BufferWriter/PrintWriter的使用演示：<br><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BufferReaderAndWriterDemo</span> </span>&#123;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException</span>&#123;</div><div class="line">		BufferedReader br = <span class="keyword">new</span> BufferedReader(<span class="keyword">new</span> InputStreamReader(<span class="keyword">new</span> FileInputStream(<span class="string">"demo/reader.txt"</span>)));</div><div class="line">		BufferedWriter bw = <span class="keyword">new</span> BufferedWriter(<span class="keyword">new</span> OutputStreamWriter(<span class="keyword">new</span> FileOutputStream(<span class="string">"demo/writer.txt"</span>)));</div><div class="line">		<span class="comment">//PrintWriter的此构造函数对上述的构造函数进行了简单的包装，才得以可以直接使用文件名</span></div><div class="line">		PrintWriter pw = <span class="keyword">new</span> PrintWriter(<span class="string">"demo/writer1.txt"</span>);</div><div class="line">		String line ;</div><div class="line">		<span class="keyword">while</span>((line = br.readLine()) != <span class="keyword">null</span>) &#123;</div><div class="line">			bw.write(line);</div><div class="line">			bw.newLine();<span class="comment">//使用BufferedWriter时需要手动换行，该类并不会自动换行</span></div><div class="line">			pw.println(line);<span class="comment">//使用PrintWriter可以自动换行</span></div><div class="line">		&#125;</div><div class="line">		br.close();</div><div class="line">		bw.close();</div><div class="line">		pw.close();</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>#对象的序列化，反序列化</p>
<ul>
<li><p>对象序列化，就是将Object转换成byte序列，反之叫对象的反序列化 </p>
</li>
<li><p>序列化流(ObjectOutputStream),是过滤流—-writeObject;反序列化流(ObjectInputStream)—readObject</p>
</li>
<li><p>序列化接口(Serializable)对象必须实现序列化接口 ，才能进行序列化，否则将出现异常;这个接口，没有任何方法，只是一个标准</p>
</li>
<li><p>transient关键字 :被transient修饰的成员变量不会自动被序列化，若想序列化该成员变量，需要手动序列化</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">writeObject</span><span class="params">(java.io.ObjectOutputStream s)</span> <span class="keyword">throws</span> IOException </span>&#123;</div><div class="line">	s.defaultWriteObject();<span class="comment">//把jvm能默认序列化的元素进行序列化操作</span></div><div class="line">	s.writeInt(stuage);<span class="comment">//自己完成stuage的序列化</span></div><div class="line">&#125;</div><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">readObject</span><span class="params">(java.io.ObjectInputStream s)</span> <span class="keyword">throws</span> ClassNotFoundException, IOException </span>&#123;</div><div class="line">	s.defaultReadObject();<span class="comment">//把jvm能默认反序列化的元素进行反序列化操作</span></div><div class="line">	<span class="keyword">this</span>.stuage = s.readInt();<span class="comment">//自己完成stuage的反序列化操作</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line">* 序列化中子类和父类构造函数的调用问题</div><div class="line">    * 对子类对象进行反序列化操作时，如果其父类没有实现序列化接口，那么其父类的构造函数将会被调用</div><div class="line">    * 一个子类实现了序列化接口，那么其子类都可以进行序列化</div><div class="line"></div><div class="line">对象序列化、反序列化演示代码：</div><div class="line"></div><div class="line">对象类</div><div class="line">​```java</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Student</span> <span class="keyword">implements</span> <span class="title">Serializable</span></span>&#123;</div><div class="line">	<span class="keyword">private</span> String stuno;</div><div class="line">	<span class="keyword">private</span> String stuname;</div><div class="line">	<span class="comment">//该元素不会进行jvm默认的序列化,也可以自己完成这个元素的序列化</span></div><div class="line">	<span class="keyword">private</span> <span class="keyword">transient</span> <span class="keyword">int</span> stuage;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="title">Student</span><span class="params">()</span></span>&#123;</div><div class="line">		</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="title">Student</span><span class="params">(String stuno, String stuname, <span class="keyword">int</span> stuage)</span> </span>&#123;</div><div class="line">		<span class="keyword">super</span>();</div><div class="line">		<span class="keyword">this</span>.stuno = stuno;</div><div class="line">		<span class="keyword">this</span>.stuname = stuname;</div><div class="line">		<span class="keyword">this</span>.stuage = stuage;</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getStuno</span><span class="params">()</span> </span>&#123;</div><div class="line">		<span class="keyword">return</span> stuno;</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setStuno</span><span class="params">(String stuno)</span> </span>&#123;</div><div class="line">		<span class="keyword">this</span>.stuno = stuno;</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getStuname</span><span class="params">()</span> </span>&#123;</div><div class="line">		<span class="keyword">return</span> stuname;</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setStuname</span><span class="params">(String stuname)</span> </span>&#123;</div><div class="line">		<span class="keyword">this</span>.stuname = stuname;</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getStuage</span><span class="params">()</span> </span>&#123;</div><div class="line">		<span class="keyword">return</span> stuage;</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setStuage</span><span class="params">(<span class="keyword">int</span> stuage)</span> </span>&#123;</div><div class="line">		<span class="keyword">this</span>.stuage = stuage;</div><div class="line">	&#125;</div><div class="line">	<span class="meta">@Override</span></div><div class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</div><div class="line">		<span class="keyword">return</span> <span class="string">"Student [stuno="</span> + stuno + <span class="string">", stuname="</span> + stuname + <span class="string">", stuage="</span> + stuage + <span class="string">"]"</span>;</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">writeObject</span><span class="params">(java.io.ObjectOutputStream s)</span> <span class="keyword">throws</span> IOException </span>&#123;</div><div class="line">		s.defaultWriteObject();<span class="comment">//把jvm能默认序列化的元素进行序列化操作</span></div><div class="line">		s.writeInt(stuage);<span class="comment">//自己完成stuage的序列化</span></div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">readObject</span><span class="params">(java.io.ObjectInputStream s)</span> <span class="keyword">throws</span> ClassNotFoundException, IOException </span>&#123;</div><div class="line">		s.defaultReadObject();<span class="comment">//把jvm能默认反序列化的元素进行反序列化操作</span></div><div class="line">		<span class="keyword">this</span>.stuage = s.readInt();<span class="comment">//自己完成stuage的反序列化操作</span></div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>操作类：<br><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ObjectSeriaDemo</span> </span>&#123;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, ClassNotFoundException</span>&#123;</div><div class="line">		String file = <span class="string">"demo/obj.dat"</span>;</div><div class="line">		ObjectOutputStream oos = <span class="keyword">new</span> ObjectOutputStream(<span class="keyword">new</span> FileOutputStream(file));</div><div class="line">		Student stu = <span class="keyword">new</span> Student(<span class="string">"10001"</span>, <span class="string">"Tony"</span>, <span class="number">20</span>);</div><div class="line">		Student stu1 = <span class="keyword">new</span> Student(<span class="string">"10002"</span>, <span class="string">"chenzitong"</span>, <span class="number">22</span>);</div><div class="line">		oos.writeObject(stu);</div><div class="line">		oos.writeObject(stu1);</div><div class="line">		oos.flush();</div><div class="line">		oos.close();</div><div class="line">		ObjectInputStream ois = <span class="keyword">new</span> ObjectInputStream(<span class="keyword">new</span> FileInputStream(file));</div><div class="line">		Student student =  (Student) ois.readObject();</div><div class="line">		System.out.println(student);</div><div class="line">		System.out.println(ois.readObject());</div><div class="line">		ois.close();</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>至此，通过对Java中IO流的学习，大概的了解到了各个流大致的关系和如何配合使用各个流进行字节或字符的读取操作，也学习到了如何手动的去序列化被transient修饰的成员变量！</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/JAVA/" rel="tag"># JAVA</a>
          
            <a href="/tags/IO/" rel="tag"># IO</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/18/Java基础--Socket/" rel="next" title="Java基础--Socket">
                <i class="fa fa-chevron-left"></i> Java基础--Socket
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/08/20/Java多线程（一）/" rel="prev" title="Java多线程（一）">
                Java多线程（一） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="uyan_frame"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avater.png"
               alt="Tony" />
          <p class="site-author-name" itemprop="name">Tony</p>
           
              <p class="site-description motion-element" itemprop="description">学习技术，分享技术...</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">29</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">25</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/zitongchen" rel="external nofollow" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#File类"><span class="nav-number">1.</span> <span class="nav-text">File类</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#RandomAccessFile"><span class="nav-number">2.</span> <span class="nav-text">RandomAccessFile</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Java文件模型"><span class="nav-number">2.1.</span> <span class="nav-text">Java文件模型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#基本类型的序列化"><span class="nav-number">2.2.</span> <span class="nav-text">基本类型的序列化</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#字节流"><span class="nav-number">3.</span> <span class="nav-text">字节流</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io" rel="external nofollow">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fastclick/1.0.6/fastclick.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazyload/1.9.3/jquery.lazyload.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  
    

    
      <!-- UY BEGIN -->
      <script type="text/javascript" src="http://v2.uyan.cc/code/uyan.js?uid=2130825"></script>
      <!-- UY END -->
    
  





  



  
  

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("4wyUmphSKE5wrQGHEh5Js0bk-gzGzoHsz", "oTOHrhMuED5U0oqV2KrRMGF0");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  


  
</body>
</html>
